/**
 * The file for the Driver class.
 */

package edu.gatech.interaction;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Random;
import java.util.Scanner;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;

import edu.gatech.information.MarketPlace;
import edu.gatech.information.Player;
import edu.gatech.information.Universe;

/**
 * This is the Driver class.
 * @author Hippie Mind Control
 * @version 1.0
 */
public class Driver extends JPanel {
	public enum State{START_SCREEN, BUILD_PLAYER_SCREEN, LOAD_GAME_SCREEN, UNIVERSE_SCREEN, ST_MINIGAME_SCREEN, MARKETPLACE_SCREEN, CURRENT_PLANET_SCREEN, PLAYER_INFO_SCREEN};
	
	private int num;
	
	/** The state of the game */
	private State gameState;

	/** The player */
	private Player player;
	
	/** The universe */
	private Universe universe;

	/** The buttons for the start screen */
	private Button newGameButton;
	private Button loadGameButton;

	/** The buttons for the build player screen */
	private Button nameButton;
	private Button incPilotButton;
	private Button decPilotButton;
	private Button incTraderButton;
	private Button decTraderButton;
	private Button incFighterButton;
	private Button decFighterButton;
	private Button incEngineerButton;
	private Button decEngineerButton;
	private Button gameEasyButton;
	private Button gameNormalButton;
	private Button gameHardButton;
	private Button submitPlayerButton;

	/** The buttons for the load screen */
	private Button fileOneButton;
	private Button fileTwoButton;
	private Button fileThreeButton;
	
	/** The buttons for the universe screen */
	private Button saveGameButton;
	private Button playerInfoButton;
	private Button currentPlanetInfoButton;
	private Button marketplaceButton;
	
	/** The space travel minigame */
	private SpaceTravelMiniGame stMiniGame;

	/** The buttons for the marketplace screen */
	private Button[] marketBuyButtons;
	private Button[] marketSellButtons;
	private Button backButton;

	/** Is the name box selected? */
	private boolean nameBoxSelected;

	/** The number of unused skill points */
	private int unusedSkillPoints;
	
	/** The different player skills */
	private int tempPilotSkill;
	private int tempTraderSkill;
	private int tempFighterSkill;
	private int tempEngineerSkill;

	/** The information for tooltips */
	private int labelX;
	private int labelY;
	private String labelString;
	
	/** Index of the planet trying to be reached */
	private int nextPlanetIndex;

	/** The difficulty level */
	private int difficulty;
	
	/** Are keys down? */
	private boolean upKeyPressed, downKeyPressed;
	
	/** The timer */
	private Timer timer;
	
	/**
	 * Initiates all buttons and variables.
	 */
	public Driver() {
		gameState = State.START_SCREEN;

		addKeyListener(new KeyInputAdapter());
		setFocusable(true);
		addMouseListener(new MouseInputAdapter());
		addMouseMotionListener(new MouseMotion());
		timer = new Timer(50, new TimerListener());

		newGameButton = new Button(100, 350, 200, 100, "New Game");
		loadGameButton = new Button(500, 350, 200, 100, "Load Game");
		
		fileOneButton = new Button(250, 100, 300, 100, "File 1");
		fileTwoButton = new Button(250, 250, 300, 100, "File 2");
		fileThreeButton = new Button(250, 400, 300, 100, "File 3");
		
		nameButton = new Button(250, 30, 300, 100, "(name)");
		incPilotButton = new Button(50, 255, 30, 30, "+");
		decPilotButton = new Button(90, 255, 30, 30, "-");
		incTraderButton = new Button(50, 315, 30, 30, "+");
		decTraderButton = new Button(90, 315, 30, 30, "-");
		incFighterButton = new Button(50, 375, 30, 30, "+");
		decFighterButton = new Button(90, 375, 30, 30, "-");
		incEngineerButton = new Button(50, 435, 30, 30, "+");
		decEngineerButton = new Button(90, 435, 30, 30, "-");
		gameEasyButton = new Button(500, 250, 200, 50, "Easy");
		gameNormalButton = new Button(500, 330, 200, 50, "Normal");
		gameHardButton = new Button(500, 410, 200, 50, "Hard");
		submitPlayerButton = new Button(300, 500, 200, 50, "Submit");

		saveGameButton = new Button(740, 2, 50, 50, "");
		saveGameButton.setVisible(false);
		playerInfoButton = new Button(50, 500, 200, 50, "Player Info");
		currentPlanetInfoButton = new Button(300, 500, 200, 50, "Planet Info");
		marketplaceButton = new Button(550, 500, 200, 50, "Marketplace");

		stMiniGame = new SpaceTravelMiniGame();
		
		marketBuyButtons = new Button[11];
		marketSellButtons = new Button[11];
		for(int i = 0; i < 11; i++) {
			marketBuyButtons[i] = new Button(425, 148 + i * 30, 100, 28, "Buy");
			marketSellButtons[i] = new Button(675, 148 + i * 30, 100, 28, "Sell");
		}
		backButton = new Button(300, 500, 200, 50, "Back");

		nameBoxSelected = false;

		unusedSkillPoints = 20;
		tempPilotSkill = 0;
		tempFighterSkill = 0;
		tempTraderSkill = 0;
		tempEngineerSkill = 0;

		labelString = "";

		nextPlanetIndex = -1;
		
		difficulty = -1;
	}
	/**
	 * Draws the screens.
	 */
	public void paintComponent(Graphics g)
	{
		super.paintComponent(g);
		Graphics2D g2d = (Graphics2D)g;
		
		ImageIcon background = new ImageIcon("src/edu/gatech/interaction/galaxyBackground.jpg");
		Image image = background.getImage();
		g2d.drawImage(image,0,0,this);

		switch(gameState)
		{ 
		case START_SCREEN:
			g2d.setColor(Color.WHITE);
			g2d.setFont(new Font("Trebuchet MS", Font.PLAIN, 100));
			g2d.drawString("Space", 270, 100);
			g2d.drawString("Traders", 230, 200);
			newGameButton.draw(g2d);
			loadGameButton.draw(g2d);
			break;

		case BUILD_PLAYER_SCREEN:
			nameButton.draw(g2d);
			g2d.setColor(Color.BLUE);
			g2d.drawLine(400, 150, 400, 480);

			g2d.setColor(Color.WHITE);
			g2d.setFont(new Font("Trebuchet MS", Font.PLAIN, 25));
			g2d.drawString("Unused Skill Points: "+unusedSkillPoints, 50, 210);
			g2d.drawString("Pilot Skill: " + tempPilotSkill, 130, 280);
			g2d.drawString("Trader Skill: " + tempTraderSkill, 130, 340);
			g2d.drawString("Fighter Skill: " + tempFighterSkill, 130, 400);
			g2d.drawString("Engineer Skill: " + tempEngineerSkill, 130, 460);
			incPilotButton.draw(g2d);
			decPilotButton.draw(g2d);
			incTraderButton.draw(g2d);
			decTraderButton.draw(g2d);
			incFighterButton.draw(g2d);
			decFighterButton.draw(g2d);
			incEngineerButton.draw(g2d);
			decEngineerButton.draw(g2d);

			g2d.setColor(Color.WHITE);
			g2d.setFont(new Font("Trebuchet MS", Font.ITALIC, 25));
			g2d.drawString("Difficulty ", 540, 210);
			gameEasyButton.draw(g2d);
			gameNormalButton.draw(g2d);
			gameHardButton.draw(g2d);

			submitPlayerButton.draw(g2d);
			break;

		case LOAD_GAME_SCREEN:
			fileOneButton.draw(g2d);
			fileTwoButton.draw(g2d);
			fileThreeButton.draw(g2d);
			break;
			
		case UNIVERSE_SCREEN:
			universe.drawPlanets(g2d, player.getPlanetLocated());
			saveGameButton.draw(g2d);
			playerInfoButton.draw(g2d);
			currentPlanetInfoButton.draw(g2d);
			marketplaceButton.draw(g2d);
			g2d.setColor(Color.WHITE);
			g2d.setFont(new Font("Trebuchet MS", Font.PLAIN, 50));
			labelX = (labelX + (labelString.length()*30)) > 800 ? (labelX + (800-(labelX + (labelString.length()*30)))) : labelX; 
			g2d.drawString(labelString, labelX, labelY);
			g2d.drawString("Current Planet: " + player.getPlanetLocated().getName(), 120, 50);
			background = new ImageIcon("src/edu/gatech/interaction/Save-icon.png");
			image = background.getImage();
			g2d.drawImage(image, 742, 4, this);
			break;
			
		case ST_MINIGAME_SCREEN:
			stMiniGame.draw(g2d, this);
			break;

		case CURRENT_PLANET_SCREEN:
			g2d.setColor(Color.WHITE);
			g2d.setFont(new Font("Trebuchet MS", Font.PLAIN, 50));
			g2d.drawString("Current Planet Information", 90, 75);
			g2d.setFont(new Font("Trebuchet MS", Font.PLAIN, 30));
			g2d.drawString("Name: " + player.getPlanetLocated().getName(), 25, 170);
			g2d.drawString("Economy: " + player.getPlanetLocated().getEconomy(), 25, 220);
			g2d.drawString("Government: " + player.getPlanetLocated().getGovernment(), 25, 270);
			g2d.drawString("Special Resource: " + player.getPlanetLocated().getSpecialResource(), 25, 320);
			backButton.draw(g2d);
			break;

		case PLAYER_INFO_SCREEN:
			g2d.setColor(Color.WHITE);
			g2d.setFont(new Font("Trebuchet MS", Font.PLAIN, 50));
			g2d.drawString("Player Information - " + player.getName(), 115, 75);
			g2d.setFont(new Font("Trebuchet MS", Font.PLAIN, 30));
			g2d.drawString("Pilot Skill: " + player.getPilotSkill(), 25, 150);
			g2d.drawString("Trader Skill: " + player.getTraderSkill(), 25, 180);
			g2d.drawString("Fighter Skill: " + player.getFighterSkill(), 25, 210);
			g2d.drawString("Engineer Skill: " + player.getEngineerSkill(), 25, 240);
			g2d.setFont(new Font("Trebuchet MS", Font.PLAIN, 50));
			g2d.drawString("Player Ship Information", 125, 315);
			g2d.setFont(new Font("Trebuchet MS", Font.PLAIN, 30));
			g2d.drawString("Ship Type: " + player.getShip().getShipType(), 25, 390);
			g2d.drawString("Cargo Bay Size: " + player.getShip().getCargoBaySize(), 25, 420);
			g2d.drawString("Ship Speed: " + player.getShip().getShipSpeed(), 25, 450);
			backButton.draw(g2d);
			break;

		case MARKETPLACE_SCREEN:
			g2d.setColor(Color.WHITE);
			g2d.setFont(new Font("Trebuchet MS", Font.PLAIN, 50));
			g2d.drawString("Marketplace", 260, 45);
			g2d.drawLine(200, 95, 200, 475);
			g2d.drawLine(550, 95, 550, 475);
			g2d.drawLine(25, 145, 775, 145);
			g2d.setFont(new Font("Trebuchet MS", Font.ITALIC, 25));
			g2d.drawString("Goods:", 25, 140);
			g2d.drawString("Market Has:", 225, 140);
			g2d.drawString("You Have:", 575, 140);
			g2d.setFont(new Font("Trebuchet MS", Font.PLAIN, 25));
			MarketPlace marketplace = player.getPlanetLocated().getMarketplace();
			for(int i = 0; i < 11; i++)
			{
				g2d.drawString(""+MarketPlace.ResourceType.values()[i], 25, 175 + i * 30);
				marketBuyButtons[i].draw(g2d);
				g2d.drawString(""+marketplace.getFinalStock()[i] + " @ $" + marketplace.getFinalPrice()[i], 225, 175 + i * 30);
				marketSellButtons[i].draw(g2d);
				if(i == 10)
				{
					g2d.drawString(""+player.getShip().getCurrentFuel(), 575, 175 + i * 30);
				}
				else
				{
					g2d.drawString(""+player.getShip().getCargo()[i], 575, 175 + i * 30);
				}
			}
			g2d.drawString("Money: $"+player.getMoney(), 25, 525);
			g2d.drawString("Empty CargoBays: "+ (player.getShip().getCargoBaySize() - player.getShip().totalCargo()), 520, 525);

			backButton.draw(g2d);
			break;
		}
	}

	/**
	 * Main method that creates the JFrame and sets the size of the game screen.
	 * @param args
	 */
	public static void main(String[] args)
	{
		Driver driver = new Driver();
		JFrame frame = new JFrame("Space Trader");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.add(driver);
		frame.pack();

		frame.setSize(new Dimension(800, 600));
		frame.setResizable(false);
		frame.setVisible(true);
	}
	/**
	 * Highlights the name input box when player presses the mouse over it.
	 *
	 */
	private class KeyInputAdapter extends KeyAdapter
	{
		public void keyPressed(KeyEvent e)
		{
			switch(gameState)
			{
			case BUILD_PLAYER_SCREEN:
				if(nameBoxSelected)
				{
					String tempName = nameButton.getText();
					if(e.getKeyCode() == KeyEvent.VK_BACK_SPACE && tempName.length() > 0)
						tempName = tempName.substring(0, tempName.length() - 1);
					else if(isValid(e.getKeyChar()))
						tempName += e.getKeyChar();
					nameButton.setText(tempName);
					repaint();
				}
				break;
			
			case ST_MINIGAME_SCREEN:
				if(e.getKeyCode() == KeyEvent.VK_UP)
					upKeyPressed = true;
				else if(e.getKeyCode() == KeyEvent.VK_DOWN)
					downKeyPressed = true;
				break;
			}
		}
		
		public void keyReleased(KeyEvent e)
		{
			if(e.getKeyCode() == KeyEvent.VK_UP)
				upKeyPressed = false;
			else if(e.getKeyCode() == KeyEvent.VK_DOWN)
				downKeyPressed = false;
		}

		public boolean isValid(char key)
		{
			return(key == '-' || key == ' ' || key == '.' || (key >= '0' && key <= '9') || (key >= 'A' && key <= 'Z') || (key >= 'a' && key <= 'z'));
		}
	}

	/**
	 * Determines if a button has been moved
	 */
	private class MouseMotion implements MouseMotionListener
	{
		public void mouseMoved(MouseEvent e)
		{   
			switch(gameState)
			{
			case UNIVERSE_SCREEN:
				boolean flag = false;
				String temp = "";
				for(int i = 0; i < universe.getPlanetCount(); i++) {
					if(universe.getPlanet(i).contains(e.getX(),e.getY())){
						labelX = e.getX();
						labelY = e.getY();
						temp = universe.getPlanet(i).getName();
						flag = true;
					}
				}
				if(flag) {
					labelString = temp;
				} else {
					labelString = "";
				}
			}
			repaint();
		}

		@Override
		public void mouseDragged(MouseEvent e) {
			// TODO Auto-generated method stub

		}
	}

	/**
	 * Determines if a button has been pressed and updates the screen appropriately.
	 *
	 */
	private class MouseInputAdapter extends MouseAdapter implements MouseMotionListener
	{
		public void mouseClicked(MouseEvent e)
		{
			switch(gameState)
			{
			case START_SCREEN:
				if(newGameButton.contains(e.getX(), e.getY()))
					gameState = State.BUILD_PLAYER_SCREEN;   
				else if(loadGameButton.contains(e.getX(), e.getY()))
				{
					if(JOptionPane.showOptionDialog(null, 
							"Would you like to load from previous save?", 
							"Load", 
							JOptionPane.YES_NO_OPTION, 
							JOptionPane.QUESTION_MESSAGE, 
							null, null, null) == JOptionPane.YES_OPTION)
					{
						try {
							player = new Player();
							universe = new Universe();
							Scanner scan = new Scanner(new File("test.txt"));
							String nextLine = scan.nextLine();
							player.loadString(nextLine);
							String[] input = nextLine.split(",");
							
							nextLine = scan.nextLine();
							universe.loadString(nextLine);
							universe.getPlanet(0).setName("Acamar");
							universe.getPlanet(1).setName("Adahn");
							universe.getPlanet(2).setName("Aldea");
							universe.getPlanet(3).setName("Andevian");
							universe.getPlanet(4).setName("Antedi");
							universe.getPlanet(5).setName("Balosnee");
							player.setPlanetLocated(universe.getPlanetByName(input[6]));
							
							repaint();
							JOptionPane.showMessageDialog(null, "Load Success");
						} catch(Exception x) {
							JOptionPane.showMessageDialog(null, "Load Failed");
							x.printStackTrace();
						}
						System.out.println(player.name);
						gameState = State.UNIVERSE_SCREEN;
						//gameState = state.LOAD_GAME_SCREEN;
					}
				}
				break;

			case BUILD_PLAYER_SCREEN:
				if(nameButton.contains(e.getX(), e.getY()))
				{
					nameButton.setButtonColor(Color.WHITE);
					nameButton.setTextColor(Color.BLACK);
					nameBoxSelected = true;
				}
				else
				{
					nameButton.setButtonColor(Color.GRAY);
					nameButton.setTextColor(Color.WHITE);
					nameBoxSelected = false;
				}
				if(incPilotButton.contains(e.getX(), e.getY()))
				{
					if(tempPilotSkill < 10 && unusedSkillPoints > 0)
					{
						tempPilotSkill++;
						unusedSkillPoints--;
					}
				}
				else if(decPilotButton.contains(e.getX(), e.getY()))
				{
					if(tempPilotSkill > 0)
					{
						tempPilotSkill--;
						unusedSkillPoints++;
					}
				}
				else if(incTraderButton.contains(e.getX(), e.getY()))
				{
					if(tempTraderSkill < 10 && unusedSkillPoints > 0)
					{
						tempTraderSkill++;
						unusedSkillPoints--;
					}
				}
				else if(decTraderButton.contains(e.getX(), e.getY()))
				{
					if(tempTraderSkill > 0)
					{
						tempTraderSkill--;
						unusedSkillPoints++;
					}
				}
				else if(incFighterButton.contains(e.getX(), e.getY()))
				{
					if(tempFighterSkill < 10 && unusedSkillPoints > 0)
					{
						tempFighterSkill++;
						unusedSkillPoints--;
					}
				}
				else if(decFighterButton.contains(e.getX(), e.getY()))
				{
					if(tempFighterSkill > 0)
					{
						tempFighterSkill--;
						unusedSkillPoints++;
					}
				}
				else if(incEngineerButton.contains(e.getX(), e.getY()))
				{
					if(tempEngineerSkill < 10 && unusedSkillPoints > 0)
					{
						tempEngineerSkill++;
						unusedSkillPoints--;
					}
				}
				else if(decEngineerButton.contains(e.getX(), e.getY()))
				{
					if(tempEngineerSkill > 0)
					{
						tempEngineerSkill--;
						unusedSkillPoints++;
					}
				}
				else if(gameEasyButton.contains(e.getX(), e.getY())) {
					gameEasyButton.setButtonColor(Color.CYAN);
					gameNormalButton.setButtonColor(Color.GRAY);
					gameHardButton.setButtonColor(Color.GRAY);
					difficulty = 0;
				}
				else if(gameNormalButton.contains(e.getX(), e.getY())) {
					gameEasyButton.setButtonColor(Color.GRAY);
					gameNormalButton.setButtonColor(Color.CYAN);
					gameHardButton.setButtonColor(Color.GRAY);
					difficulty = 1;
				}
				else if(gameHardButton.contains(e.getX(), e.getY())) {
					gameEasyButton.setButtonColor(Color.GRAY);
					gameNormalButton.setButtonColor(Color.GRAY);
					gameHardButton.setButtonColor(Color.CYAN);
					difficulty = 2;
				}
				else if(submitPlayerButton.contains(e.getX(), e.getY()))
				{
					if(nameButton.getText().length() == 0)
					{
						JOptionPane.showMessageDialog(null, "Please give your character a name.");
					}
					else if(nameButton.getText() == "(name)")
					{
						JOptionPane.showMessageDialog(null, "Don't you want to give your character a more original name ");
					}
					else if(unusedSkillPoints != 0)
					{
						JOptionPane.showMessageDialog(null, "Make sure to use all of your skill points before continuing.");
					}
					else if(difficulty == -1)
					{
						JOptionPane.showMessageDialog(null, "Please select a difficulty.");
					}
					else
					{
						universe = new Universe();
						universe.generateUniverse();
						player = new Player(nameButton.getText(), tempPilotSkill, tempTraderSkill, tempFighterSkill, tempEngineerSkill, universe.getPlanet(0));
						gameState = State.UNIVERSE_SCREEN;
					}
				}
				break;
			
			case LOAD_GAME_SCREEN:
				if(fileOneButton.contains(e.getX(), e.getY()))
				{
					try {
						player = new Player();
						universe = new Universe();
						Scanner scan = new Scanner(new File("test.txt"));
						String nextLine = scan.nextLine();
						player.loadString(nextLine);
						String[] input = nextLine.split(",");
						
						nextLine = scan.nextLine();
						universe.loadString(nextLine);
						universe.getPlanet(0).setName("Acamar");
						universe.getPlanet(1).setName("Adahn");
						universe.getPlanet(2).setName("Aldea");
						universe.getPlanet(3).setName("Andevian");
						universe.getPlanet(4).setName("Antedi");
						universe.getPlanet(5).setName("Balosnee");
						player.setPlanetLocated(universe.getPlanetByName(input[6]));
						
						repaint();
						JOptionPane.showMessageDialog(null, "Load Success");
					} catch(Exception x) {
						JOptionPane.showMessageDialog(null, "Load Failed");
						x.printStackTrace();
					}
					System.out.println(player.name);
					gameState = State.UNIVERSE_SCREEN;
				}
				break;
			
			case UNIVERSE_SCREEN:
				if(marketplaceButton.contains(e.getX(), e.getY()))
				{
					gameState = State.MARKETPLACE_SCREEN;
				}
				else if(saveGameButton.contains(e.getX(), e.getY()))
				{
					try{
						PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(new File("test.txt"))));
						writer.println(player.saveString());
						writer.println(universe.saveString());
						writer.flush();
						writer.close();
						JOptionPane.showMessageDialog(null, "Save Success");
					} catch(Exception x) {
						JOptionPane.showMessageDialog(null, "Save Failed");
					}
					System.out.println(player.name);
				}
				else if(playerInfoButton.contains(e.getX(), e.getY()))
				{
					gameState = State.PLAYER_INFO_SCREEN;
				}
				else if(currentPlanetInfoButton.contains(e.getX(), e.getY()))
				{
					gameState = State.CURRENT_PLANET_SCREEN;
				}
				for(int i = 0; i < universe.getPlanetCount(); i++) {
					if(universe.getPlanet(i).contains(e.getX(),e.getY())){
						//						final JOptionPane optionPane = new JOptionPane(
						//							    "Destionation Planet: " + universe.getPlanet(i).getName() + "\nWould you like to warp to this planet?",
						//							    JOptionPane.QUESTION_MESSAGE,
						//							    JOptionPane.YES_NO_OPTION);
						String content =
								"\nName: " + universe.getPlanet(i).getName() +
								"\nEconomy: " + universe.getPlanet(i).getEconomy() +
								"\nGovernment: " + universe.getPlanet(i).getGovernment() +
								"\nSpecial Resource: " + universe.getPlanet(i).getSpecialResource();
						int choice = JOptionPane.showOptionDialog(null, 
								"Would you like to warp to planet " + universe.getPlanet(i).getName() + "?\n" + content, 
								"Warp Menu", 
								JOptionPane.YES_NO_OPTION, 
								JOptionPane.QUESTION_MESSAGE, 
								null, null, null);
						if (choice == JOptionPane.YES_OPTION) {
							if (player.getPlanetLocated().getName().equals(universe.getPlanet(i).getName())){
								JOptionPane.showMessageDialog(null,
										"You are already on that planet!",
										"Message",
										JOptionPane.ERROR_MESSAGE);
							} else if (player.inRange(universe.getPlanet(i))){
								gameState = State.ST_MINIGAME_SCREEN;
								stMiniGame.start(2 * player.fuelToReach(universe.getPlanet(i)));
								timer.start();
								nextPlanetIndex = i;
							} else {
								JOptionPane.showMessageDialog(null,
										"Your ship does not have enough fuel!",
										"Message",
										JOptionPane.ERROR_MESSAGE);
							}
						}

					}
				}
				break;
				
			case CURRENT_PLANET_SCREEN:
				if(backButton.contains(e.getX(), e.getY()))
				{
					gameState = State.UNIVERSE_SCREEN;
				}
				break;

			case PLAYER_INFO_SCREEN:
				if(backButton.contains(e.getX(), e.getY()))
				{
					gameState = State.UNIVERSE_SCREEN;
				}
				break;

			case MARKETPLACE_SCREEN:
				if(backButton.contains(e.getX(), e.getY()))
				{
					gameState = State.UNIVERSE_SCREEN;
				}
				MarketPlace marketplace = player.getPlanetLocated().getMarketplace();
				for(int i = 0; i < 11; i++)
				{
					if(marketBuyButtons[i].contains(e.getX(), e.getY()))
					{
						if(player.getMoney() >= marketplace.getFinalPrice()[i])
						{
							if(marketplace.getFinalStock()[i] > 0)
							{
								if(i == 10) {
									//ME
								/*	if(player.getShip().canAddFuel()) {
										player.setMoney(player.getMoney() - marketplace.getFinalPrice()[i]);
										player.getShip().setCurrentFuel(player.getShip().getCurrentFuel()+1);
										marketplace.removeStockFrom(i);
									}
									else
									{
										JOptionPane.showMessageDialog(null, "Your fuel tank is full.");
									}*/
									if(player.addFuel(marketplace)){
										marketplace.removeStockFrom(10);
									}
									else {
										JOptionPane.showMessageDialog(null, "Your fuel tank is full.");
									}
								}
								else if(player.getShip().canAddCargo())
								{
									player.setMoney(player.getMoney() - marketplace.getFinalPrice()[i]);
									player.getShip().addCargoTo(i);
									marketplace.removeStockFrom(i);
								}
								else
								{
									JOptionPane.showMessageDialog(null, "Your cargo bay is full.");
								}
							}
							else
							{
								JOptionPane.showMessageDialog(null, "The market is out of that resource.");
							}
						}
						else
						{
							JOptionPane.showMessageDialog(null, "You don't have enough money!");
						}
					}
					else if(marketSellButtons[i].contains(e.getX(), e.getY()))
					{
						if(i == 10)
						{
							/*if(player.getShip().getCurrentFuel() > 0)
							{
								player.setMoney(player.getMoney() + marketplace.getFinalPrice()[i]);
								player.getShip().setCurrentFuel(player.getShip().getCurrentFuel()-1);
								marketplace.addStockTo(i);
							}
							else
							{
								JOptionPane.showMessageDialog(null, "You don't have any of that to sell!");
							}*/
							if(player.removeFuel(marketplace))
							{
								marketplace.addStockTo(i);
							}
							else
							{
								JOptionPane.showMessageDialog(null, "You don't have any of that to sell!");
							}
						}
						else if(player.getShip().getCargo()[i] > 0)
						{
							player.setMoney(player.getMoney() + marketplace.getFinalPrice()[i]);
							player.getShip().removeCargoFrom(i);
							marketplace.addStockTo(i);
						}
						else
						{
							JOptionPane.showMessageDialog(null, "You don't have any of that to sell!");
						}
					}
				}
				break;
			}
			repaint();
		}
	}
	
	private class TimerListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			if(e.getSource() == timer)
			{
				if(upKeyPressed)
					stMiniGame.moveShipUp();
				else if(downKeyPressed)
					stMiniGame.moveShipDown();
				stMiniGame.step();
				repaint();
				if(stMiniGame.isGameOver())
				{
					timer.stop();
					gameState = State.UNIVERSE_SCREEN;
					upKeyPressed = false;
					downKeyPressed = false;
					repaint();
					if(stMiniGame.isWin())
					{
						int randEvent = new Random().nextInt(100);
						if (randEvent < 10) {
							JOptionPane.showMessageDialog(null,
									"A corrupt customs official fines you 10% of your current money to enter " + universe.getPlanet(nextPlanetIndex).getName() + ".",
									"Random Event", JOptionPane.INFORMATION_MESSAGE);
							player.setMoney((int) (player.getMoney()- player.getMoney()*.1));
							player.setPlanetLocated(universe.getPlanet(nextPlanetIndex));
						} 
						else if (randEvent < 20 & randEvent >= 10) {
							JOptionPane.showMessageDialog(null,
									"You encountered a meteor shower, and only survived because of excellent piloting.  Your pilot skill has increased.",
									"Random Event", JOptionPane.INFORMATION_MESSAGE);
							player.setPilotSkill(player.getPilotSkill() + 1);
							player.setPlanetLocated(universe.getPlanet(nextPlanetIndex));
						}
						else if (randEvent < 30 & randEvent >= 20) {
							JOptionPane.showMessageDialog(null,
									"You had to take a deteor on your path to " + universe.getPlanet(nextPlanetIndex).getName() + " due to a broken down spaceship.  You used more fuel than expected.",
									"Random Event", JOptionPane.INFORMATION_MESSAGE);
							player.getShip().setCurrentFuel(player.getShip().getCurrentFuel() - player.getShip().getCurrentFuel()/2);
							player.setPlanetLocated(universe.getPlanet(nextPlanetIndex));
						}
						else if (randEvent < 40 & randEvent >= 30) {
							JOptionPane.showMessageDialog(null,
									"When you get to " + universe.getPlanet(nextPlanetIndex).getName() + " you see aliens playing poker, you join the game and win $55.",
									"Random Event", JOptionPane.INFORMATION_MESSAGE);
							player.setMoney(player.getMoney() + 50);
							player.setPlanetLocated(universe.getPlanet(nextPlanetIndex));
						}
						else if (randEvent < 70 & randEvent >= 50) {
							int choice = JOptionPane.showOptionDialog(null,
									"On your way to " + universe.getPlanet(nextPlanetIndex).getName() + " you encountered the POLICE. They would like to search your ship for any illegal goods, do you agree to the search?",
									"THE POLICE", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,null,null);
							if (choice == JOptionPane.YES_OPTION) {
								//int[] getCargo() 
								if (player.getShip().getCargo()[5] > 0) {
									//YOU HAVE FIREARMS
									JOptionPane.showMessageDialog(null,
											"THEY FOUND FIREARMS ON YOUR SHIP! Lucky for you, the police officer is corrupt and fines you 30% of your current money.",
											"Random Event", JOptionPane.INFORMATION_MESSAGE);
									player.setMoney((int) (player.getMoney() - player.getMoney()*0.3));
								}
								else if (player.getShip().getCargo()[8] > 0) {
									//YOU HAVE DRUGS
									JOptionPane.showMessageDialog(null,
											"THEY FOUND NARCOTICS ON YOUR SHIP! Lucky for you, the police officer is corrupt and fines you 50% of your current money.",
											"Random Event", JOptionPane.INFORMATION_MESSAGE);
									player.setMoney((int) (player.getMoney() - player.getMoney()*0.5));
								}
								else {
									JOptionPane.showMessageDialog(null,
											"The police didn't find anything.  You continue on your way.",
											"Random Event", JOptionPane.INFORMATION_MESSAGE);
								}
								player.setPlanetLocated(universe.getPlanet(nextPlanetIndex));
							}
							if (choice == JOptionPane.NO_OPTION) {
								JOptionPane.showMessageDialog(null,
										"When you inform the police that they can not search your ship, they begin to fire on you!  You flee for your life and dump all your cargo in order to make it to " + universe.getPlanet(nextPlanetIndex).getName() + " safely.",
										"Random Event", JOptionPane.INFORMATION_MESSAGE);
								int [] tempCar = new int [] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
								player.getShip().setCargo(tempCar);
								player.setPlanetLocated(universe.getPlanet(nextPlanetIndex));
							}
							
						} else if (randEvent < 90 & randEvent >= 70) {
							int choice = JOptionPane.showOptionDialog(null,
									"On your way to " + universe.getPlanet(nextPlanetIndex).getName() + " you encountered A TRADER. They would like to trade with you, do you agree to the trade?",
									"A TRADER", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,null,null);
							if (choice == JOptionPane.YES_OPTION) {
								//int[] getCargo() 
								if (player.getShip().getCargo()[5] > 0) {
									//YOU HAVE FIREARMS
									JOptionPane.showMessageDialog(null,
											"YOU GAINED 10% PROFIT FROM TRADING WITH THEM!",
											"Random Event", JOptionPane.INFORMATION_MESSAGE);
									player.setMoney((int) (player.getMoney() + player.getMoney()*0.1));
								}
								else if (player.getShip().getCargo()[8] > 0) {
									//YOU HAVE DRUGS
									JOptionPane.showMessageDialog(null,
											"YOU ACCIDENTLY ROBBED THE TRADER AND STOLE ALL THEIR GOODS!",
											"Random Event", JOptionPane.INFORMATION_MESSAGE);
									player.setMoney((int) (player.getMoney() + player.getMoney()*0.5));
								}
								else {
									JOptionPane.showMessageDialog(null,
											"The trader doesn't like anything you have.",
											"Random Event", JOptionPane.INFORMATION_MESSAGE);
								}
								player.setPlanetLocated(universe.getPlanet(nextPlanetIndex));
							}
							if (choice == JOptionPane.NO_OPTION) {
								JOptionPane.showMessageDialog(null,
										"When you inform the trader you didn't want to trade, they revealed their true identity as a pirate and attacked you. You abandonned all your goods to fleed to " + universe.getPlanet(nextPlanetIndex).getName() + " safely.",
										"Random Event", JOptionPane.INFORMATION_MESSAGE);
								int [] tempCar = new int [] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
								player.getShip().setCargo(tempCar);
								player.setPlanetLocated(universe.getPlanet(nextPlanetIndex));
							}
							
						} else {
							player.setPlanetLocated(universe.getPlanet(nextPlanetIndex));
						}
					}
					else
					{
						if(stMiniGame.isPirateHit())
						{
							JOptionPane.showMessageDialog(null, "You were attacked by pirates who took half of your money! Fortunately, you escaped with the rest and made your way back to " + player.getPlanetLocated().getName());
							player.setMoney(player.getMoney() / 2);
						}
						else
							JOptionPane.showMessageDialog(null, "You hit an asteroid, but fortunately you drifted back to " + player.getPlanetLocated().getName());
						nextPlanetIndex = -1;
					}
				}
			}
		}
	}
}